package com.example.demo.lamada;

import lombok.extern.log4j.Log4j;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述
 *
 * @author: yuy
 */
@Log4j
public class MapStreamTest {

    public static List<TestUser> data = Arrays.asList(
        new TestUser(1L, "aaa"),
        new TestUser(2L, "bbb"),
        new TestUser(3L, "ccc"),
        new TestUser(4L, "ddd"),
        new TestUser(2L, "eee"),
        new TestUser(4L, "fff"),
        new TestUser(5L, "gggg"));

    @Test
    public void test1() { //java.lang.IllegalStateException: Duplicate key bbb
        Map<Long, String> map = data.stream().collect(Collectors.toMap(TestUser::getId, TestUser::getUsername));
        log.info(map);
    }

    @Test
    public void test2() {
        Map<Long, String> map = data.stream().collect(
            Collectors.toMap(TestUser::getId, TestUser::getUsername, (oldValue, newValue) -> oldValue)
        );
        log.info(map);
    }

    @Test
    public void test3() {//{1=[aaa], 2=[bbb, eee], 3=[ccc], 4=[ddd, fff], 5=[gggg]}
        Map<Long, List<String>> map = data.stream().collect(
            Collectors.groupingBy(TestUser::getId,
                Collectors.mapping(TestUser::getUsername, Collectors.toList())));
        log.info(map);
    }

    @Test
    public void test4() {//{1=[aaa], 2=[bbb, eee], 3=[ccc], 4=[ddd, fff], 5=[gggg]}
        Map<Long, List<String>> map = data.stream().collect(
            Collectors.toMap(TestUser::getId, e -> new ArrayList<>(Arrays.asList(e.getUsername())),
                (List<String> oldList, List<String> newList) -> {
                    oldList.addAll(newList);
                    return oldList;
                }));
        log.info(map);
    }

}
